package com.sc.nft.task;

import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.OrderGasService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 刘国航
 * @desc
 * @since 2024/10/21 16:33
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderGasShareTask {

    private final RedissonClient redissonClient;
    private final OrderGasService orderGasService;

    /**
     * 更新上链费分红池
     */
    @XxlJob("refreshOrderGasPool")
    public void refreshGasPool() {
        RLock lock = redissonClient.getLock(RedisKeyEnum.ORDER_GAS_SHARE_TASK.getKey());
        try {
            boolean res = lock.tryLock(30, TimeUnit.SECONDS);
            if (!res) {
                throw new GlobalException("上链费分红处理中！！！！");
            }
            orderGasService.refreshOrderGasPool();
        } catch (Exception e) {
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    /**
     * 发放上链费分红
     */
    @XxlJob("rewardsOrderGas")
    public void rewardsOrderGas() {
        RLock lock = redissonClient.getLock(RedisKeyEnum.ORDER_GAS_SHARE_TASK.getKey());
        try {
            boolean res = lock.tryLock(30, TimeUnit.SECONDS);
            if (!res) {
                throw new GlobalException("上链费分红处理中！！！！");
            }
            orderGasService.rewardsOrderGas();
        } catch (Exception e) {
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}
